import React,{useState, useEffect} from 'react'
import './mfSetting.css'
import { Drawer, Switch, Table, Button} from 'antd'
import {ToolFilled} from '@ant-design/icons'
import {EditableCell, EditableRow} from './EditableCell'
import {getNeoEntrys} from './getNeoEntrys'
import 'antd/dist/antd.less'
import Helper from './helper';
import { Tabs } from 'antd';

declare global {
    interface Window {
        neoEntrys: {
            [propName: string]: string
        }
    }
}

function getItemByLocalStorage(key){
    const neoEntrys = localStorage.getItem('neoEntrys');
    if(!neoEntrys){
        return null;
    }
    try{
        return JSON.parse(neoEntrys)[key]
    }catch(e){
        return null;
    }
}

/**
 * 合并localStorage
 * @param key 
 * @param value 
 * @param original 
 */
function mergeLocalStorage(key,value, originalNeoEntrys){
    const neoEntrys = localStorage.getItem('neoEntrys');
    let obj = {[key]: value};
    if(neoEntrys){
       obj =  JSON.parse(neoEntrys);
       obj = {...obj,...{[key]:value}}
    }
    //如果要设置的value 和初始值值一样，就删掉该值
    if(originalNeoEntrys[key] === value){
        delete obj[key];
    }
    if(Object.keys(obj).length){
        localStorage.setItem('neoEntrys', JSON.stringify(obj))
    }else{
        localStorage.removeItem('neoEntrys')
    }
}


export default function(props){
    const [neoEntrys,setNeoEntrys] = useState(false);
    const [drawerOpen,setDrawerOpen] = useState(false);
    const [dataSourceH5,setDataSourceH5] = useState([
        {
            name: 'neo_ui_component_h5_bi',
            key: 'neo_ui_component_h5_bi',
            project: 'neo-ui-h5component-basebi',
            port: 3300,
            url: ''
        },
        {
            name: 'neo_ui_component_sfa_h5',
            key: 'neo_ui_component_sfa_h5',
            project: 'neo-ui-component-sfa',
            port: 3333,
            url: ''
        },
        {
            name: 'neo_ui_component_h5_scrm',
            key: 'neo_ui_component_h5_scrm',
            project: 'neo-apps-scrmplatform-fe',
            port: 4400,
            url: ''
        },
        {
            name: 'neo_ui_component_prm_h5',
            key: 'neo_ui_component_prm_h5',
            project: 'neo-ui-component-prm',
            port: 4300,
            url: ''
        },
        {
            name: 'neo_ui_component_servicecloud_h5',
            key: 'neo-ui-component-servicecloud-h5',
            project: 'neo-ui-component-servicecloud',
            port: 3432,
            url: ''
        },
        {
            name: 'neo_ui_component_h5',
            project: 'xsy-neo-ui-component',
            key: 'neo_ui_component_h5',
            port: 3300,
            url: ''
        },
    ])
    const [dataSource,setDataSource] = useState([
        {
            name: 'neo_ui_component_web_bi',
            key: 'neo_ui_component_web_bi',
            project: 'neo-ui-webcomponent-basebi',
            port: 3300,
            url: ''
        },
        {
            name: 'neo_ui_component_sfa_web',
            key: 'neo_ui_component_sfa_web',
            project: 'neo-ui-component-sfa',
            port: 3333,
            url: ''
        },
        {
            name: 'neo_ui_component_web_scrm',
            key: 'neo_ui_component_web_scrm',
            project: 'neo-apps-scrmplatform-fe',
            port: 4400,
            url: ''
        },
        {
            name: 'neo_ui_component_prm_web',
            key: 'neo_ui_component_prm_web',
            project: 'neo-ui-component-prm',
            port: 4300,
            url: ''
        },
        {
            name: 'neo_ui_component_servicecloud_web',
            key: 'neo-ui-component-servicecloud-web',
            project: 'neo-ui-component-servicecloud',
            port: 3433,
            url: ''
        },
        {
            name: 'neo_ui_component_web',
            project: 'xsy-neo-ui-component',
            key: 'neo_ui_component_web',
            port: 3300,
            url: ''
        },
        {
            name: 'neo_ui_icon',
            key: 'neo_ui_icon',
            project: 'neo-platform-ui-icon',
            port: 2900,
            url: ''
        },
        {
            name: 'neobase',
            key: 'neobase',
            project: 'neo-platform-ui-cli',
            port: 3009,
            url: ''
        },
        {
            name: 'neoreact',
            key: 'neoreact',
            project: 'neo-platform-ui-cli',
            port: 3911,
            url: ''
        },
    ]);

    /**
     * 获取原始neoEntry
     */
    useEffect(()=>{
        getNeoEntrys().then(data=>{
            setNeoEntrys(data);
            const newData =  dataSource.map(item=>{
                //代理优先
                const proxyurl = getItemByLocalStorage(item.key)
                item.url = proxyurl || data[item.key];
                return item;
            });
            setDataSource(newData);

            const h5Data =  dataSourceH5.map(item=>{
                //代理优先
                const proxyurl = getItemByLocalStorage(item.key)
                item.url = proxyurl || data[item.key];
                return item;
            });
            setDataSourceH5(h5Data);
        }).catch(e=>{

        })
    },[])
    const handleSave = (row) => {
        console.log('地址变为：',row)
        const newData = [...dataSource];
        const index = newData.findIndex(item => row.key === item.key);
        const item = newData[index];
        newData.splice(index, 1, {
        ...item,
        ...row,
        });
        setDataSource(newData);
        mergeLocalStorage(row.key,row.url,neoEntrys)
    };


    function getColumns(dataSource, setDataSource){
        const defaultColumns = [
            {
            title: '组件名称',
            dataIndex: 'name',
            width: 200,
            key: 'name',
            },
            {
            title: '地址',
            dataIndex: 'url',
            width: 400,
            editable: true,
            key: 'url',
            render: (text, record) => (
                <div style={{ wordWrap: 'break-word', wordBreak: 'break-word' }}>
                {text}
                </div>
            ),
            },
            {
                title: '本地调试',
                width: 100,
                key: 'operation',
                render:(_,record)=>{
                    // console.log('record.url==', record.url)
                    // console.log('neoEntrys==', neoEntrys[record.key])
                    return <Switch checked={record.url !== neoEntrys[record.key]} onChange={(open)=>{
                        setDataSource(dataSource.map(data=>{
                            if(data.name === record.name){
                                if(open){
                                    data.url = `https://localhost:${record.port}/remoteEntry.js`
                                }else{
                                    data.url = neoEntrys[record.key];
                                }
                                mergeLocalStorage(record.key, data.url, neoEntrys);
                            }
                            return data
                        }));
                    }}></Switch>
                }
            },
            {
                title: '调用Demo',
                dataIndex: 'helper',
                key: 'helper',
                render: (text, record) =>{
                    return <Helper record={record}/>
                }
            },
            {
                title: 'Gerrit',
                dataIndex: 'gerrit',
                key: 'gerrit',
                render: (text, record) =>{
                    const match = record.url?.match(/remoteEntry.(\S*).js/);
                    let commitId
                    if(match?.length > 0){
                         commitId = record.url?.match(/remoteEntry.(\S*).js/)[1]
                    }
                    return (
                        <div>
                        <Button onClick={()=>{
                            window.open(
                                `https://gerrit.ingageapp.com/gitweb?p=${record.project}.git;a=commit;h=${commitId}`
                              )
                        }}>提交记录</Button>
                        </div>
                    )
                },
            }
        ];
    
        const columns = defaultColumns.map(col => {
            if (!col.editable) {
              return col;
            }
            return {
              ...col,
              onCell: (record) => ({
                record,
                editable: col.editable,
                dataIndex: col.dataIndex,
                title: col.title,
                handleSave,
              }),
            };
          });
      return columns    
    }  
    return (
        <div className='mf-setting-container'>
            <Button icon={<ToolFilled />} onClick={()=>setDrawerOpen(true)}/>
            <Drawer title="模块联邦调试" visible={drawerOpen} onClose={()=>{
                 setDrawerOpen(false)
                 window.location.reload()
            }} width={'90%'}>
                <Tabs defaultActiveKey="1">
                    <Tabs.TabPane tab="Web" key="1">
                        <Table 
                            components={{
                                body: {
                                    row: EditableRow,
                                    cell: EditableCell,
                                }
                            }}
                            bordered
                            rowClassName={() => 'editable-row'}
                            dataSource={dataSource}
                            columns={getColumns(dataSource, setDataSource)} />
                    </Tabs.TabPane>
                    <Tabs.TabPane tab="H5" key="2">
                        <Table 
                                components={{
                                    body: {
                                        row: EditableRow,
                                        cell: EditableCell,
                                    }
                                }}
                                bordered
                                rowClassName={() => 'editable-row'}
                                dataSource={dataSourceH5}
                                columns={getColumns(dataSourceH5, setDataSourceH5)} />
                    </Tabs.TabPane>
                </Tabs>
               
            </Drawer>
        </div>)
}